package cn.neu.leon.util;


import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;


public class WeiboCookies {
	
	private final static String COOKIES = "./library/cookies";
	public static Map<String,String> getSinaCookie()
    throws Exception
  {
    
    HtmlUnitDriver driver = new HtmlUnitDriver();
    driver.setJavascriptEnabled(true);
    driver.get("http://login.weibo.cn/login/");
//    String username = "18563911485";
//    String password = "kll123456";
    
    String username = "13314208296";
    String password = "13314208296";
    
    WebElement mobile = driver.findElementByCssSelector("input[name=mobile]");
    mobile.sendKeys(new CharSequence[] { username });
    WebElement pass = driver.findElementByCssSelector("input[name^=password]");
    pass.sendKeys(new CharSequence[] { password });
    WebElement rem = driver.findElementByCssSelector("input[name=remember]");
    rem.click();
    WebElement submit = driver.findElementByCssSelector("input[name=submit]");
    submit.click();

    Set<Cookie> cookieSet = driver.manage().getCookies();
    Map<String,String> cookiesMap = new HashMap<String,String>();
    driver.close();
    for (Cookie cookie : cookieSet) {
        cookiesMap.put(cookie.getName(), cookie.getValue());      
    	//sb.append(new StringBuilder().append(cookie.getName()).append("=").append(cookie.getValue()).append(";").toString());
    }
    //String result = sb.toString();
    
    //写入文件
    ObjectOutputStream ops = new ObjectOutputStream(new FileOutputStream(COOKIES));
    ops.writeObject(cookiesMap);
    ops.flush();
    ops.close();
    
    
    if (cookiesMap.containsKey("gsid_CTandWM")) {
      return cookiesMap;
    }
    throw new Exception("weibo login failed");
  }
	
	public static HashMap<String,String> read() {
		try {
			File file = new File(COOKIES);
			if(!file.exists()) return null;
			else{
				FileInputStream fis = new FileInputStream(file);
				ObjectInputStream oin = new ObjectInputStream(fis);
				HashMap<String,String> temp = (HashMap<String, String>) oin.readObject();
				fis.close();
				oin.close();
				return temp;
			}
		} catch (EOFException e) {
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			return null;
		}
	}
}

